﻿using Ionic.Zlib;
using System.IO;
namespace ServerFramework.Tools
{
    public class Zip
    {
        public static byte[] zip(byte[] data)
        {
            MemoryStream memstream = new MemoryStream(data);
            MemoryStream outstream = new MemoryStream();

            using (GZipStream encoder = new GZipStream(outstream, CompressionMode.Compress,CompressionLevel.BestCompression))
            {
                memstream.WriteTo(encoder);
            }

            return outstream.ToArray();
        }

        public static byte[] unzip(byte[] data)
        {
            GZipStream decoder = new GZipStream(new MemoryStream(data), CompressionMode.Decompress, CompressionLevel.BestCompression);
            MemoryStream outstream = new MemoryStream();
            CopyStream(decoder, outstream);
            return outstream.ToArray();
        }

        private static void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[512];
            //long TempPos = input.Position;
            while (true)
            {
                int read = input.Read(buffer, 0, buffer.Length);
                if (read <= 0) break;
                output.Write(buffer, 0, read);
            }
            //input.Position = TempPos;// or you make Position = 0 to set it at the start 
        }

    }
}
